<?php
namespace App\Service\H5;

class DepartService extends BaseService
{
    //数据列表
    public static function index($pas)
    {
        $db = self::dbConn(self::$dbStDepart)->where('del', 0);
        if (isset($pas['depart_id']) && $pas['depart_id']) {
            $db = $db->where('depart_id', $pas['depart_id']);
        }
        $res = $db->get();
        if (!count($res)) {
            return self::toback(-2, '数据不存在');
        }
        $arys = [];
        foreach ($res as $v) {
            $arys[] = [
                'id' => $v->id, 'title' => $v->title,
            ];
        }
        return self::toback(0, '', $arys);
    }

    //新增
    public static function add($title)
    {
        $res = self::dbConn(self::$dbStDepart)
            ->where('title', $title)
            ->first();
        if (!empty($res)) {
            return self::toback(-2, '存在同名数据');
        }
        $res = self::dbConn(self::$dbStDepart)->insertGetId([
            'title' => $title, 'addtime' => toDate(), 'uptime' => toDate(),
        ]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    //修改
    public static function modify($id, $title)
    {
        $res = self::dbConn(self::$dbStDepart)->where('id', $id)->first();
        if (empty($res)) {
            return self::toback(-2, '数据不存在');
        }
        $res = self::dbConn(self::$dbStDepart)
            ->where('title', $title)
            ->where('id', '<>', $id)
            ->first();
        if (!empty($res)) {
            return self::toback(-2, '存在同名数据');
        }
        $res = self::dbConn(self::$dbStDepart)
            ->where('id', $id)
            ->update(['title' => $title, 'uptime' => toDate()]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    //删除
    public static function del($id)
    {
        $res = self::dbConn(self::$dbStDepart)->where('id', $id)->first();
        if (empty($res)) {
            return self::toback(-2, '数据不存在');
        }
        $res = self::dbConn(self::$dbStDepart)
            ->where('id', $id)
            ->update(['del' => 1, 'deltime' => toDate()]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }
}